from app import create_app
from config import get_config
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask import request, jsonify
import ssl

app = create_app(get_config())

# 配置SSL会话缓存
ssl_context = ssl.create_default_context()
ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2  # 使用TLS 1.2及以上版本
ssl_context.set_ciphers('ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305')
try:
    ssl_context.load_dh_params('ssl/dhparam.pem')  # 加载DH参数
except Exception as e:
    print(f"加载DH参数时出错: {e}")

# 添加请求限速器
limiter = Limiter(
    get_remote_address,
    app=app,
    default_limits=["1000 per day", "200 per hour"],  # 增加默认限制
    storage_uri="memory://",
)

# 队列管理
MAX_CONCURRENT_REQUESTS = 500  # 增加最大并发请求数
current_requests = 0

@app.before_request
def limit_concurrent_requests():
    global current_requests
    # 跳过静态文件请求和音频块上传请求
    if request.path.startswith('/static/') or request.path.startswith('/api/upload_chunk'):
        return None
    
    if current_requests >= MAX_CONCURRENT_REQUESTS:
        return jsonify({
            "error": "服务器当前负载过高，请稍后再试",
            "status": "overloaded"
        }), 503
    
    current_requests += 1

@app.after_request
def after_request(response):
    global current_requests
    # 跳过静态文件请求和音频块上传请求
    if not request.path.startswith('/static/') and not request.path.startswith('/api/upload_chunk'):
        current_requests -= 1
    
    # 为所有响应添加安全相关的头部
    response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['X-Frame-Options'] = 'SAMEORIGIN'
    return response

# 修改上传路由的限制
@limiter.limit("30 per minute")  # 增加每分钟允许的上传次数
@app.route('/upload', methods=['POST'])
def limited_upload():
    # 这会重写原来的视图函数，我们需要导入并调用原函数
    from app.views import upload
    return upload()

if __name__ == "__main__":
    app.run(ssl_context=ssl_context) 